#!/bin/bash
set -e

## FUNCTIONS

diagnostic()
{
     echo "$@" 1>&2;
}

checkfail()
{
    if [ ! $? -eq 0 ];then
        diagnostic "$1"
        exit 1
    fi
}

get_symbol()
{
    echo "$1" | grep vlc_entry_$2 | cut -d " " -f 3
}

source emsdk/emsdk_env.sh

if [ ! -d vlc ]; then
    diagnostic "vlc must exists. Execute compile.sh"
	exit 1
fi

cd vlc

PROJECT_DIR=$(pwd)
NM="$EMSDK/upstream/bin/llvm-nm"

cd build-emscripten/modules/.libs

# create module list
echo "creating module list"
touch $PROJECT_DIR/build-emscripten/vlc-modules.c
echo -e "// This file is autogenerated" > $PROJECT_DIR/build-emscripten/vlc-modules.c
echo -e "#include <unistd.h>\n\n" >> $PROJECT_DIR/build-emscripten/vlc-modules.c


BUILTINS="const void *vlc_static_modules[] = {\n"
LDFLAGS=""
DEFINITIONS=""
VLCMODULES=""
i=""

for i in `ls *plugin.a`
do
    VLCMODULES="$i $VLCMODULES"
done

for file in $VLCMODULES
    do
        symbols=$($NM -g $file)
        entryname=$(get_symbol "$symbols" _)
        DEFINITIONS+="int $entryname (int (*)(void *, void *, int, ...), void *);\n";
        BUILTINS+=" $entryname,\n"
        LDFLAGS+="\$PROJECT_DIR/build-emscripten/modules/.libs/$file "
    done;

cd ../..

BUILTINS="$BUILTINS NULL\n};\n"

echo -e "$DEFINITIONS\n$BUILTINS" >> $PROJECT_DIR/build-emscripten/vlc-modules.c
